
#include "ESP8266.h"
#include "dht11.h"
#include "SoftwareSerial.h"
#include <ArduinoJson.h>

//配置ESP8266WIFI设置
#define SSID "HUAWEI-004SM7"    
#define PASSWORD "zw932564"//填写自己的WIFI密码
#define HOST_NAME "api.heclouds.com"  //API主机名称，连接到OneNET平台
#define DEVICE_ID "859459085"       
#define HOST_PORT (80)                //API端口，连接到OneNET平台，无需修改
String APIKey = "QB6OAO=1m10T7Ay90MuBVzlxsx4="; 
int stream1;                           //用于存放返回的数值back
int n = 0;

#define INTERVAL_SENSOR 100 //定义传感器采样及发送时间间隔

SoftwareSerial mySerial(3, 2);
ESP8266 wifi(mySerial);
//
// 读取数据 -- Read data
//
int readData(char dId[])
{

   String send_data = "GET /devices/";
       send_data += dId;
       send_data += "/datapoints?datastream_id=X HTTP/1.1";
       send_data += "\r\n";
       send_data += "api-key:";
       send_data += APIKey;
       send_data += "\r\n";
       send_data += "Host:api.heclouds.com\r\n";
       send_data += "Connection:close\r\n\r\n";

  const char *postarray = send_data.c_str(); //将str转化为char数组
  Serial.println(send_data);
  bool httpResponse = wifi.send((const uint8_t *)postarray, strlen(postarray)); 
  Serial.println("send success");
  postarray = NULL; //清空数组，等待下次传输数据
  uint8_t buffer[512] = {0};
  int x=0;
  char a="";
  uint32_t len = wifi.recv(buffer, sizeof(buffer), 20000);
  if (len > 0)
  {
    for (uint32_t i = 0; i < len; i++) {
      Serial.print((char)buffer[i]);
      if ((char)buffer[i] == 'v' && (char)buffer[i + 1] == 'a' && (char)buffer[i + 2] == 'l' && (char)buffer[i + 3] == 'u' && (char)buffer[i + 4] == 'e')    
      {     a=(char)buffer[i + 7];
        if(a=='1')
      x=1;
      if(a=='0')
      x=0;
      }
      }
    }
    //便于观察返回数据
    Serial.println("");
    Serial.print("x:");
    Serial.print(x);
    
  return x;
}


//
// 上传数据 -- Send data
//
void sendData(float sensor_lig,char dId[])
{
  char buf[10];
       //拼接发送data字段字符串
       String jsonToSend = "{\"Lighting\":";
       dtostrf(sensor_lig, 1, 2, buf);
       jsonToSend += "\"" + String(buf) + "\"";
       jsonToSend += "}";

       //拼接POST请求字符串
       String postString = "POST /devices/";
       postString += dId;
       postString += "/datapoints?type=3 HTTP/1.1";
       postString += "\r\n";
       postString += "api-key:";
       postString += APIKey;
       postString += "\r\n";
       postString += "Host:api.heclouds.com\r\n";
       postString += "Connection:close\r\n";
       postString += "Content-Length:";
       postString += jsonToSend.length();
       postString += "\r\n";
       postString += "\r\n";
       postString += jsonToSend;
       postString += "\r\n";
       postString += "\r\n";
       postString += "\r\n";

       const char *postArray = postString.c_str(); //将str转化为char数组

       Serial.println(postArray);
       wifi.send((const uint8_t *)postArray, strlen(postArray)); 
       Serial.println("send success");
       postArray = NULL; //清空数组，等待下次传输数据
  }



void setup()
{
  mySerial.begin(115200); //初始化软串口
  Serial.begin(9600);     //初始化串口
  pinMode(10, OUTPUT); //设置输出口
  Serial.print("setup begin\r\n");

  //以下为ESP8266初始化的代码
  //  Serial.print("FW Version: ");
  //  Serial.println(wifi.getVersion().c_str());

  if (wifi.setOprToStation()) {
    Serial.print("to station ok\r\n");
  } else {
    Serial.print("to station err\r\n");
  }

  //ESP8266接入WIFI
  if (wifi.joinAP(SSID, PASSWORD)) {
    Serial.print("Join AP success\r\n");
    Serial.print("IP: ");
    Serial.println(wifi.getLocalIP().c_str());
  } else {
    Serial.print("Join AP failure\r\n");
  }

  Serial.println("");
  Serial.print("DHT11 LIBRARY VERSION: ");
  Serial.println(DHT11LIB_VERSION);

  mySerial.println("AT+UART_CUR=9600,8,1,0,0");
  mySerial.begin(9600);
  Serial.println("setup end\r\n");
}

unsigned long net_time1 = millis(); //数据上传服务器时间


void loop() {
  float lighting = analogRead(A3);   //读取模拟口A3，获取光强
  //Serial.println(lighting);               // 用于IDE串口观察窗

  if (net_time1 > millis())
    net_time1 = millis();

  if (millis() - net_time1 > INTERVAL_SENSOR) //发送数据时间间隔
  {
    float sensor_lig = (float)lighting;

      Serial.print("Lighting : ");
      Serial.println(sensor_lig, 2);

      n=n+1;

    if (wifi.createTCP(HOST_NAME, HOST_PORT)) { //建立TCP连接，如果失败，不能发送该数据
      Serial.print("create tcp ok\r\n");
      //交叉传输和接收数据，减小硬件负担
      if(n%2==1)
      stream1 = readData(DEVICE_ID);
      Serial.print("stream1");
      Serial.println(stream1);
      if(n%2==0)
      sendData(sensor_lig,DEVICE_ID);
       
      if (wifi.releaseTCP()) { //释放TCP连接
         Serial.print("release tcp ok\r\n");
       } else {
         Serial.print("release tcp err\r\n");
       }
      net_time1 = millis();
      }
      else {
       Serial.print("create tcp err\r\n");
      }
  }
  if(stream1==1&&lighting<=350)
    digitalWrite(10,HIGH);
    else
    digitalWrite(10,LOW);
    delay(100);       //防止串口写入速度过快
}
